package org.opens.netty.chatServer.client;

import cn.hutool.core.lang.hash.Hash;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.opens.netty.chatServer.message.*;
import org.opens.netty.chatServer.protocol.MessageCodecSharable;
import org.opens.netty.chatServer.protocol.ProtocolFrameDecoder;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class Client1 {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup worker = new NioEventLoopGroup();

        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC_SHARABLE = new MessageCodecSharable();

        // 可以使线程阻塞等待的计数器
        CountDownLatch waitForLogin = new CountDownLatch(1);
        // 使用原子类来进行线程间通信
        AtomicBoolean loginFlag = new AtomicBoolean();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(worker);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProtocolFrameDecoder());
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC_SHARABLE);
                    // 参数1: 若干秒内没有收到client发来的数据就会触发一个事件-{@link IdleState#READER_IDLE}; 参数2: 若干秒内没有向channel写入数据就认为空闲了; 参数3: 若干秒内没有发生任何读写事件
                    // 3秒内没有向server写数据则触发一个{@link IdleState#WRITER_IDLE}事件, 这里写的间隔要比server那边配置的时间短
                    ch.pipeline().addLast(new IdleStateHandler(0, 3, 0));
                    // ChannelDuplexHandler可以同时作为入站处理器和出站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        /**
                         * 用来处理特殊事件, 比如说IdleState#READER_IDLE
                         * 这里的逻辑相当于是-只要3秒内没有向服务器发送消息, 则发送一个心跳包, 证明自己是活的, 没有发生连接假死
                         */
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            // 判断事件类型
                            if (event.state() == IdleState.WRITER_IDLE) {
                                //log.info("3秒没有写数据了, client触发了IdleState.WRITER_IDLE事件, 发送一个心跳包.");
                                ctx.writeAndFlush(new PingMessage());
                            }
                        }
                    });
                    ch.pipeline().addLast("clientHandle", new ChannelInboundHandlerAdapter() {

                        /**
                         * 接受服务端的消息
                         */
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            //log.info("client接受: {}, 类型: {}", msg, msg.getClass());

                            if (msg instanceof LoginResponseMessage) {
                                LoginResponseMessage loginResponseMessage = (LoginResponseMessage) msg;
                                // 如果登录成功
                                if (loginResponseMessage.isSuccess()) {
                                    loginFlag.set(true);
                                }
                                // 使阻塞等待计数器减1, 唤醒对应的线程
                                waitForLogin.countDown();;
                            }
                        }

                        /**
                         * 连接建立后会触发这个事件
                         */
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            // 负责接受用户在控制台的输入, 然后发送至服务器
                            // 用户输入是一个阻塞行为, 放在当前handle会阻塞住EventLoop
                            new Thread(() -> {
                                Scanner scanner = new Scanner(System.in);
                                System.out.println("请输入用户名:");
                                String username = scanner.nextLine();
                                System.out.println("请输入密码:");
                                String password = scanner.nextLine();

                                // 构造消息
                                LoginRequestMessage loginRequestMessage = new LoginRequestMessage(username, password);

                                // 写入channel
                                // 此处使用ctx对象写入, 会从当前handle向head逐个触发出战处理器
                                ctx.writeAndFlush(loginRequestMessage);

                                System.out.println("等待后续操作......");
                                try {
                                    // CountDownLatch中的计数不为0时, 调用await方法会进入阻塞
                                    waitForLogin.await();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                                if (!loginFlag.get()) { // 如果登录失败, 就关闭连接并退出程序
                                    ctx.close();
                                    return;
                                }

                                while (true) {
                                    // 打印菜单, 提供行为选择
                                    System.out.println("====================================");
                                    System.out.println("send [username] [content]");
                                    System.out.println("gsend [group name] [content]");
                                    System.out.println("gcreate [group name] [m1, m2, m3...]");
                                    // 获取聊天组成员
                                    System.out.println("gmembers [group name]");
                                    System.out.println("gjoin [group name]");
                                    System.out.println("gquit [group name]");
                                    System.out.println("quit [group name]");
                                    System.out.println("====================================");
                                    String command = scanner.nextLine();

                                    String[] commandArr = command.split(" ");
                                    switch (commandArr[0]) {
                                        case "send":
                                            ChatRequestMessage chatRequestMessage = new ChatRequestMessage(username, commandArr[1], commandArr[2]);
                                            ctx.writeAndFlush(chatRequestMessage);
                                            break;
                                        case "gsend":
                                            GroupChatRequestMessage groupChatRequestMessage = new GroupChatRequestMessage(username, commandArr[1], commandArr[2]);
                                            ctx.writeAndFlush(groupChatRequestMessage);
                                            break;
                                        case "gcreate":
                                            Set<String> membersSet = new HashSet<>(Arrays.asList(commandArr[2].split(",")));
                                            // 将自己也加入组中
                                            membersSet.add(username);
                                            GroupCreateRequestMessage groupCreateRequestMessage = new GroupCreateRequestMessage(commandArr[1], membersSet);
                                            ctx.writeAndFlush(groupCreateRequestMessage);
                                            break;
                                        case "gmembers":
                                            GroupMembersRequestMessage groupMembersRequestMessage = new GroupMembersRequestMessage(commandArr[1]);
                                            ctx.writeAndFlush(groupMembersRequestMessage);
                                            break;
                                        case "gjoin":
                                            GroupJoinRequestMessage groupJoinRequestMessage = new GroupJoinRequestMessage(username, commandArr[1]);
                                            ctx.writeAndFlush(groupJoinRequestMessage);
                                            break;
                                        case "gquit":
                                            GroupQuitRequestMessage groupQuitRequestMessage = new GroupQuitRequestMessage(username, commandArr[1]);
                                            ctx.writeAndFlush(groupQuitRequestMessage);
                                            break;
                                        case "quit":
                                            ctx.channel().close();
                                            break;
                                        default:
                                            break;
                                    }

                                }
                            }, "waitSystemIn").start();
                        }

                        /**
                         * 服务端主动关闭连接时触发
                         */
                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            log.info("连接已断开.");
                        }

                        /**
                         * 服务端发生异常时触发
                         */
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            log.info("连接已异常断开: {}", cause.getMessage());
                        }
                    });
                }
            });
            ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8080)).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("client error: ", e);
        } finally {
            worker.shutdownGracefully();
        }
    }
}
